package cn.com.yx.ms.controller;

import cn.com.yx.ms.application.web.ApiPager;
import cn.com.yx.ms.application.web.ApiQuery;
import cn.com.yx.ms.application.web.ApiQueryBase;
import cn.com.yx.ms.domain.dbmodel.DevEquStore;
import cn.com.yx.ms.domain.dbmodel.SysUser;
import cn.com.yx.ms.domain.live.LiveConfigMainModel;
import cn.com.yx.ms.domain.live.LiveConfigMainSavedModel;
import cn.com.yx.ms.domain.live.LiveConfigModel;
import cn.com.yx.ms.domain.live.LiveDevModel;
import cn.com.yx.ms.domain.mq.MqCommandType;
import cn.com.yx.ms.domain.mq.MqPushNoticeModel;
import cn.com.yx.ms.domain.mq.upstream.MqPushLiveConfigModel;
import cn.com.yx.ms.domain.sys.UserModel;
import cn.com.yx.ms.service.*;
import cn.yx.framework.configuration.ApiCode;
import cn.yx.framework.configuration.AppConstant;
import cn.yx.framework.configuration.BaseConstant;
import cn.yx.framework.configuration.MyWebSocket;
import cn.yx.framework.util.FileUtil;
import cn.yx.framework.util.MsgPropertyUtil;
import cn.yx.framework.view.ApiResult;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.MessageSource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;
import java.util.UUID;

import static org.springframework.web.bind.annotation.RequestMethod.GET;

/**
 * 应用中心
 */
@RestController
@RequestMapping(value = "live")
@Api(value = "直播流接口", description = "用于直播流接口")
public class LiveController {

    private static final Logger logger = LoggerFactory.getLogger(LiveController.class);

    @Resource
    private ILiveService iLiveService;
    @Resource
    private IMqService iMqService;
    @Resource
    private ILogService iLogService;
    @Resource
    private IUserContextService iUserContextService;

    private String filepath = BaseConstant.getUploadConfig().getFilepath() + "/live/config";

    @PostMapping("config")
    @ApiOperation(value = "更新直播流配置", notes = "更新直播流配置")
    @ApiImplicitParam(paramType = "body", name = "liveConfigModel", dataType = "Map", required = true, value = "测试实体详细信息")
    public ApiResult updateLastConfig(@RequestBody @Validated LiveConfigModel liveConfigModel, BindingResult bindingResult) throws Exception {

        if (liveConfigModel.getConfigid() == null || liveConfigModel.getConfigid().equals("")) {
            liveConfigModel.setConfigid(UUID.randomUUID().toString());
            if (liveConfigModel.getDevid().equals("")) {
                liveConfigModel.setDevid("common");
            }
        }

        //保存本地文件
        String jsonData = JSON.toJSONString(liveConfigModel);//String变量
        byte sendByte[] = jsonData.getBytes("UTF-8");//String转换为byte[]
        String fileName = "config-" + liveConfigModel.getDevid() + ".json";
        FileUtil.writeFile(filepath + "/" + liveConfigModel.getDevid(),
                fileName,
                sendByte);

        //推送客户端
        MyWebSocket.sendWebClientInfo(JSON.toJSONString(jsonData));

        return new ApiResult<>(AppConstant.MSG_SUCCESS, true, "", JSON.toJSONString(liveConfigModel));
    }


    @ResponseBody
    @RequestMapping("config/{devid}")
    @ApiOperation("获取最后一次直播流配置")
    public ApiResult getLastConfig(@PathVariable("devid") String devid) throws Exception {
        String decode = URLDecoder.decode(devid, "UTF-8");
        String jsonContent = FileUtil.File2String(filepath + "/" + decode + "/config-" + decode + ".json");
        LiveConfigModel liveConfigModel = JSON.parseObject(jsonContent, LiveConfigModel.class);
        return new ApiResult<>(AppConstant.MSG_SUCCESS, true, "获取成功", liveConfigModel);
    }

    @ResponseBody
    @RequestMapping("config/ips")
    @ApiOperation("获取最后一次直播流配置")
    public ApiResult getLastConfig() throws Exception {
        return new ApiResult<>(AppConstant.MSG_SUCCESS, MyWebSocket.getClientIps());
    }

    // region << 直播设备管理 >>

    @ResponseBody
    @RequestMapping(value = "equipments/page", method = RequestMethod.GET)
    @ApiOperation("获取带分页的直播设备")
    public ApiResult findEquipmentsPage(@ApiQuery ApiQueryBase query, HttpServletRequest request) {

        // 查询条件接受
        query.getConditions().put("ps", request.getParameter("ps"));
        query.getConditions().put("pi", request.getParameter("pi"));
        query.getConditions().put("sname", request.getParameter("sname"));
        query.getConditions().put("equipmentno", request.getParameter("equipmentno"));
        query.getConditions().put("status", request.getParameter("status"));

        // 翻页对象构建
        PageHelper.startPage(query.getPi(), query.getPs(), true);
        Page<LiveDevModel> page = (Page<LiveDevModel>) iLiveService.findLiveDevs(query);
        ApiPager<LiveDevModel> apiPager = new ApiPager<>(query.getPs(),
                query.getPi(),
                page.getTotal(),
                page.getResult());

        return new ApiResult<>(AppConstant.MSG_SUCCESS, true, "", apiPager);

    }

    @ResponseBody
    @RequestMapping(value = "equipments/{equipmentguid}", method = GET)
    @ApiImplicitParam(paramType = "String", name = "equipmentguid", dataType = "String", required = true, value = "设备ID")
    @ApiOperation("获取单个直播设备信息")
    public ApiResult findLiveEquipmentById(@PathVariable("equipmentguid") String equipmentguid) {
        return new ApiResult<>(AppConstant.MSG_SUCCESS, iLiveService.findLive(equipmentguid));
    }

    @PostMapping("equipment")
    @ApiOperation(value = "创建设备信息", notes = "创建直播设备信息")
    @ApiImplicitParam(paramType = "body", name = "devEquStore", dataType = "Map", required = true, value = "直播设备实体对象")
    public ApiResult createLiveEquipment(@RequestBody @Validated DevEquStore devEquStore) throws Exception {
        ApiCode apiCode = iLiveService.saveLiveDev(devEquStore);
        return new ApiResult<>(Integer.parseInt(apiCode.msgId), apiCode.equals(ApiCode.APP_100200), MsgPropertyUtil.getProperty(apiCode.msgId));
    }

    @DeleteMapping("equipments/{equipmentguid}")
    @ApiOperation(value = "删除直播设备信息", notes = "删除直播设备信息")
    @ApiImplicitParam(paramType = "path", name = "equipmentguid", dataType = "String", required = true, value = "设备ID")
    public ApiResult deleteLiveEquipment(@PathVariable("equipmentguid") String equipmentguid) {
        ApiCode apiCode = iLiveService.deleteLiveDev(equipmentguid);
        return new ApiResult<>(Integer.parseInt(apiCode.msgId), apiCode.equals(ApiCode.APP_100200), MsgPropertyUtil.getProperty(apiCode.msgId));
    }

    @PutMapping("equipment")
    @ApiOperation(value = "更新设备信息", notes = "更新设备信息")
    @ApiImplicitParam(paramType = "body", name = "devEquStore", dataType = "Map", required = true, value = "直播设备实体对象")
    public ApiResult updateLiveEquipment(@RequestBody @Validated DevEquStore devEquStore) throws Exception {
        ApiCode apiCode = iLiveService.saveLiveDev(devEquStore);
        return new ApiResult<>(Integer.parseInt(apiCode.msgId), apiCode.equals(ApiCode.APP_100200), MsgPropertyUtil.getProperty(apiCode.msgId));
    }

    @ResponseBody
    @RequestMapping(value = "equipments/{equipmentno}/configinfo", method = GET)
    @ApiImplicitParam(paramType = "String", name = "equipmentno", dataType = "String", required = true, value = "设备编号")
    @ApiOperation("获取单个直播设备信息")
    public ApiResult findEquipmentConfigInfoByNo(@PathVariable("equipmentno") String equipmentno) {
        return new ApiResult<>(AppConstant.MSG_SUCCESS, iLiveService.findLiveConfigMainModelByEquipmentNo(equipmentno));
    }


    // endregion

    // region << 配置推送 >>

    @ResponseBody
    @RequestMapping(value = "liveconfigs/page", method = RequestMethod.GET)
    @ApiOperation("获取带分页的配置信息")
    public ApiResult findLiveConfigsPage(@ApiQuery ApiQueryBase query, HttpServletRequest request) {

        // 查询条件接受
        query.getConditions().put("ps", request.getParameter("ps"));
        query.getConditions().put("pi", request.getParameter("pi"));
        query.getConditions().put("configname", request.getParameter("configname"));

        // 翻页对象构建
        PageHelper.startPage(query.getPi(), query.getPs(), true);
        Page<LiveConfigMainModel> page = (Page<LiveConfigMainModel>) iLiveService.findLiveConfigMainModels(query);
        ApiPager<LiveConfigMainModel> apiPager = new ApiPager<>(query.getPs(),
                query.getPi(),
                page.getTotal(),
                page.getResult());

        return new ApiResult<>(AppConstant.MSG_SUCCESS, true, "", apiPager);

    }

    @ResponseBody
    @RequestMapping(value = "liveconfigs/{cguid}", method = GET)
    @ApiImplicitParam(paramType = "String", name = "cguid", dataType = "String", required = true, value = "直播配置ID")
    @ApiOperation("获取直播配置信息")
    public ApiResult findLiveConfigById(@PathVariable("cguid") String cguid) {
        return new ApiResult<>(AppConstant.MSG_SUCCESS, iLiveService.findLiveConfigMainModel(cguid));
    }

    @PatchMapping("liveconfigs/{cguid}/{configname}")
    @ApiOperation(value = "直播配置信息更名", notes = "直播配置信息更名")
    public ApiResult updateLiveConfigName(@PathVariable("cguid") String cguid, @PathVariable("configname") String configname) throws Exception {
        ApiCode apiCode = iLiveService.updateLiveConfigName(cguid, URLDecoder.decode(configname, "UTF-8"));
        return new ApiResult<>(Integer.parseInt(apiCode.msgId), apiCode.equals(ApiCode.APP_100200), MsgPropertyUtil.getProperty(apiCode.msgId));
    }

    @PostMapping("config/equipment")
    @ApiOperation(value = "保存设备配置信息", notes = "保存设备配置信息")
    @ApiImplicitParam(paramType = "body", name = "liveConfigMainSavedModel", dataType = "Map", required = true, value = "直播设备实体对象")
    public ApiResult saveLiveConfig(@RequestBody @Validated LiveConfigMainSavedModel liveConfigMainSavedModel) throws Exception {
        ApiCode apiCode = iLiveService.saveLiveConfigMain(liveConfigMainSavedModel, true);
        return new ApiResult<>(Integer.parseInt(apiCode.msgId), apiCode.equals(ApiCode.APP_700500), MsgPropertyUtil.getProperty(apiCode.msgId));
    }

    @PostMapping("config/equipment/ws")
    @ApiOperation(value = "直播流配置推送", notes = "推送直播配置")
    @ApiImplicitParam(paramType = "body", name = "mqPushLiveConfigModel", dataType = "Map", required = true, value = "推送直播配置")
    public ApiResult pushLiveConfig(@RequestBody @Validated LiveConfigMainSavedModel liveConfigMainSavedModel) {
        ApiCode apiCode = iLiveService.pushLiveConfig(liveConfigMainSavedModel, true);
        return new ApiResult<>(Integer.parseInt(apiCode.msgId), apiCode.equals(ApiCode.APP_700501), MsgPropertyUtil.getProperty(apiCode.msgId));
    }

    @PostMapping("config/equipments")
    @ApiOperation(value = "保存设备配置信息", notes = "保存设备配置信息")
    @ApiImplicitParam(paramType = "body", name = "liveConfigMainSavedModel", dataType = "Map", required = true, value = "直播设备实体对象")
    public ApiResult saveLiveConfigs(@RequestBody @Validated LiveConfigMainSavedModel liveConfigMainSavedModel) throws Exception {
        ApiCode apiCode = iLiveService.saveLiveConfigMain(liveConfigMainSavedModel,false);
        return new ApiResult<>(Integer.parseInt(apiCode.msgId), apiCode.equals(ApiCode.APP_700500), MsgPropertyUtil.getProperty(apiCode.msgId));
    }

    @PostMapping("config/equipments/ws")
    @ApiOperation(value = "直播流配置推送", notes = "推送直播配置")
    @ApiImplicitParam(paramType = "body", name = "mqPushLiveConfigModel", dataType = "Map", required = true, value = "推送直播配置")
    public ApiResult pushLiveConfigs(@RequestBody @Validated LiveConfigMainSavedModel liveConfigMainSavedModel) {
        ApiCode apiCode = iLiveService.pushLiveConfig(liveConfigMainSavedModel,false);
        return new ApiResult<>(Integer.parseInt(apiCode.msgId), apiCode.equals(ApiCode.APP_700501), MsgPropertyUtil.getProperty(apiCode.msgId));
    }

    @DeleteMapping("liveconfigs/{cguid}")
    @ApiOperation(value = "删除直播配置信息", notes = "删除直播配置信息")
    @ApiImplicitParam(paramType = "path", name = "cguid", dataType = "String", required = true, value = "配置id")
    public ApiResult deleteLiveConfig(@PathVariable("cguid") String cguid) {
        ApiCode apiCode = iLiveService.deleteLiveConfig(cguid);
        return new ApiResult<>(Integer.parseInt(apiCode.msgId), apiCode.equals(ApiCode.APP_100200), MsgPropertyUtil.getProperty(apiCode.msgId));
    }
    // endregion
}